package com.senta.elasticsearch.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

/**
 * @author anyang
 * Email: 1300378587@qq.com
 * Created Date:2019-11-22 09:57
 * 测试完成，初步构建合格，功能正常
 */
@Component
public class EsUtilBuilder {

    @Autowired
    private static ElasticsearchTemplate elasticsearchTemplate;

    public static <T> EsUtil build(Class<T> buiderClass ){
        if(buiderClass == null){
            throw new NullPointerException("传入类不予许为null");
        }
        Annotation classAnnotation = buiderClass.getAnnotation(Document.class);
        Document theDocument = null;
        if(classAnnotation instanceof Document) {
            theDocument = (Document)classAnnotation ;
        }
        //获取文档注解
        if(theDocument == null){
             throw new NullPointerException("该类不是一个文档类型，需要@Document ");
        }
        String indexName = theDocument.indexName();
        String docType = theDocument.type();
        //如果获取索引和类型失败则抛出异常
        if(StringUtils.isBlank(indexName) || StringUtils.isBlank(docType)){
            throw new UnsupportedOperationException("确少相关的配置");
        }
        //寻找主键
        final Field[] fields = buiderClass.getDeclaredFields();
        Field keyField = null;
        for(Field field : fields ){
            //获取主键字段
            Annotation annotation = field.getAnnotation(org.springframework.data.annotation.Id.class);
            if(annotation != null){
                keyField = field;
                break;
            }
        }
        if(keyField == null){
            throw new UnsupportedOperationException("缺少相关主键");
        }

        return new EsUtil<T>(buiderClass,indexName,docType,toGetter(keyField.getName()),elasticsearchTemplate);
    }                                                

    public static String toGetter(String fieldname) {
        if (fieldname == null || fieldname.length() == 0) {
            return null;
        }
        /* If the second char is upper, make 'get' + field name as getter name. For example, eBlog -> geteBlog */
        if (fieldname.length() > 2) {
            String second = fieldname.substring(1, 2);
            if (second.equals(second.toUpperCase())) {
                return new StringBuffer("get").append(fieldname).toString();
            }
        }
        /* Common situation */
        fieldname = new StringBuffer("get").append(fieldname.substring(0, 1).toUpperCase())
                .append(fieldname.substring(1)).toString();
        return  fieldname;
    }
}
